package com.example.framework.websocket.core.sender.local;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.example.framework.websocket.core.message.JsonWebSocketMessage;
import com.example.framework.websocket.core.sender.WebSocketMessageSender;
import com.example.framework.websocket.core.session.NativeWebSocketHandler;
import jakarta.websocket.Session;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * 本地原生方式的 {@link WebSocketMessageSender} 实现类
 * <p>
 * 注意：仅仅适合单机场景！！！
 */
@Slf4j
@RequiredArgsConstructor
public class LocalNativeWebSocketMessageSender implements WebSocketMessageSender {

    private final NativeWebSocketHandler nativeWebSocketHandler;

    @Override
    public void sendByUserId(String userId, String messageType, String messageContent) {
        // 1. 获得 Session 列表
        List<Session> sessions = Collections.emptyList();
        if (ObjectUtil.isNotEmpty(userId)) {
            sessions = (List<Session>) nativeWebSocketHandler.getSessionList(userId);
        }
        if (ObjectUtil.isEmpty(sessions)) {
            log.info("[send][userId({}) messageType({}) messageContent({}) 未匹配到会话]", userId, messageType, messageContent);
        }
        // 2. 执行发送
        JsonWebSocketMessage message = new JsonWebSocketMessage().setType(messageType).setContent(messageContent);
        sessions.forEach(session -> session.getAsyncRemote().sendText(JSONUtil.toJsonStr(message)));
    }

    @Override
    public void sendBySessionId(String sessionId, String messageType, String messageContent) {
        Session session = nativeWebSocketHandler.getSession(sessionId);
        if (Objects.isNull(session)) {
            log.info("[send][sessionId({}) messageType({}) messageContent({}) 未匹配到会话]", sessionId, messageType, messageContent);
            return;
        }
        JsonWebSocketMessage message = new JsonWebSocketMessage().setType(messageType).setContent(messageContent);
        session.getAsyncRemote().sendText(JSONUtil.toJsonStr(message));
    }

}
